package com.asset.dispoal.file.common;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

public class FileCreateUtil {

    /**
     * 创建文件进行拷贝
     *
     * @param generatorId 文件id值
     * @param file        需要拷贝的文件
     * @param headUrl     拷贝到的头地址，返回时会忽略
     * @param appendUrl   叠加的地址
     * @return 完整应答地址
     */
    public static String copyFile(String generatorId, MultipartFile file, String headUrl, String appendUrl) {
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int month = now.getMonthValue();
        int day = now.getDayOfMonth();
        StringBuilder resolveUrl = new StringBuilder();
        resolveUrl.append("/").append(appendUrl).append("/").append(year).append("/").append(month).append("/").append(day);
        String property = headUrl + "/" + resolveUrl;
        File parentResolveFile = new File(property);
        if (!parentResolveFile.exists()) {
            parentResolveFile.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            file.transferTo(new File(property + "/" + generatorId + suffix));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return resolveUrl + "/" + generatorId + suffix;
    }
}
